from fastapi import APIRouter, Depends
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
import crud
from model.user import Schedule
from api import dependencies
from schema.schedule import IScheduleCreate, IScheduleRead, ISchedulePut
from schema.response import IPostResponseBase, IPutResponseBase
from core.exceptions import IntegrityException
router = APIRouter()


@router.get('/{task_id}')
async def get_schedules_by_task_id(task_id: int, db_session: AsyncSession = Depends(dependencies.get_db)):
    return await crud.task.get(task_id, db_session)


@router.post("/add_schedule", response_model=IPostResponseBase[IScheduleRead] | str)
async def add_schedule(schema: IScheduleCreate, db_session: AsyncSession = Depends(dependencies.get_db)):
    try:
        obj = await crud.task.create_schedule(schema, db_session)
        obj = IScheduleRead.model_validate(obj)
    except IntegrityError as err:
        raise IntegrityException
    return IPostResponseBase[IScheduleRead](data=obj)

@router.put("/modify_schedule/{schedule_id}", response_model=IPutResponseBase[None])
async def modify_schedule(schedule_id: int, schema: ISchedulePut, db_session: AsyncSession = Depends(dependencies.get_db)):
    try:
        await crud.task.modify_schedule(schedule_id, schema, db_session)
        return IPutResponseBase[None]
    except IntegrityError:
        raise IntegrityException